using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using ProductManagement.Models;
using ProductManagement.Services;

namespace ProductManagement.ViewModels
{
    public class AddProductViewModel : BindableBase, INavigationAware
    {
        private readonly IProductService _productService;
        private readonly IRegionManager _regionManager;
        private readonly IDialogService _dialogService;
        
        private Product _product = new();
        private ObservableCollection<string> _categories = new();
        private string _title = "添加产品";
        private string _saveButtonText = "保存";
        private string _statusMessage = "";
        private bool _isEditMode = false;
        private int _editingProductId = 0;

        public AddProductViewModel(IProductService productService, IRegionManager regionManager, IDialogService dialogService)
        {
            _productService = productService;
            _regionManager = regionManager;
            _dialogService = dialogService;

            // 初始化Commands
            SaveCommand = new DelegateCommand(async () => await SaveProductAsync(), CanSave);
            CancelCommand = new DelegateCommand(Cancel);
            ClearCommand = new DelegateCommand(Clear);
            
            // 导航示例Commands
            NavigateToUsersCommand = new DelegateCommand(NavigateToUsers);
            NavigateToProductsCommand = new DelegateCommand(NavigateToProducts);
            NavigateWithParametersCommand = new DelegateCommand(NavigateWithParameters);
            NavigateWithConfirmCommand = new DelegateCommand(NavigateWithConfirm);

            LoadCategories();
        }

        #region Properties

        public Product Product
        {
            get { return _product; }
            set { SetProperty(ref _product, value); }
        }

        public ObservableCollection<string> Categories
        {
            get { return _categories; }
            set { SetProperty(ref _categories, value); }
        }

        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public string SaveButtonText
        {
            get { return _saveButtonText; }
            set { SetProperty(ref _saveButtonText, value); }
        }

        public string StatusMessage
        {
            get { return _statusMessage; }
            set { SetProperty(ref _statusMessage, value); }
        }

        #endregion

        #region Commands

        public DelegateCommand SaveCommand { get; }
        public DelegateCommand CancelCommand { get; }
        public DelegateCommand ClearCommand { get; }
        
        // 导航示例Commands
        public DelegateCommand NavigateToUsersCommand { get; }
        public DelegateCommand NavigateToProductsCommand { get; }
        public DelegateCommand NavigateWithParametersCommand { get; }
        public DelegateCommand NavigateWithConfirmCommand { get; }

        #endregion

        #region Command Methods

        private bool CanSave()
        {
            return !string.IsNullOrWhiteSpace(Product.Name) && Product.Price > 0 && Product.Stock >= 0;
        }

        private async Task SaveProductAsync()
        {
            try
            {
                if (!CanSave())
                {
                    StatusMessage = "请填写必要信息";
                    return;
                }

                StatusMessage = _isEditMode ? "正在更新产品..." : "正在保存产品...";

                bool success;
                if (_isEditMode)
                {
                    Product.Id = _editingProductId;
                    success = await _productService.UpdateProductAsync(Product);
                }
                else
                {
                    success = await _productService.AddProductAsync(Product);
                }

                if (success)
                {
                    StatusMessage = _isEditMode ? "产品更新成功" : "产品保存成功";
                    
                    // 延迟一下再导航，让用户看到成功消息
                    await Task.Delay(1000);
                    _regionManager.RequestNavigate("ContentRegion", "ProductListView");
                }
                else
                {
                    StatusMessage = _isEditMode ? "产品更新失败" : "产品保存失败";
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"操作失败: {ex.Message}";
            }
        }

        private void Cancel()
        {
            _regionManager.RequestNavigate("ContentRegion", "ProductListView");
        }

        private void Clear()
        {
            if (_isEditMode) return; // 编辑模式下不允许清空

            Product = new Product();
            StatusMessage = "表单已清空";
        }

        // 导航示例方法
        private void NavigateToUsers()
        {
            _regionManager.RequestNavigate("ContentRegion", "UserListView");
            StatusMessage = "导航到用户列表";
        }

        private void NavigateToProducts()
        {
            _regionManager.RequestNavigate("ContentRegion", "ProductListView");
            StatusMessage = "导航到产品列表";
        }

        private void NavigateWithParameters()
        {
            var parameters = new NavigationParameters
            {
                { "Category", Product.Category ?? "未分类" }
            };
            _regionManager.RequestNavigate("ContentRegion", "ProductListView", parameters);
            StatusMessage = "带参数导航到产品列表";
        }

        private void NavigateWithConfirm()
        {
            var dialogParams = new DialogParameters
            {
                { "title", "导航确认" },
                { "message", "您确定要离开当前页面吗？未保存的数据将丢失。" }
            };

            _dialogService.ShowDialog("ConfirmationDialog", dialogParams, result =>
            {
                if (result.Result == ButtonResult.OK)
                {
                    _regionManager.RequestNavigate("ContentRegion", "UserListView");
                    StatusMessage = "已确认导航";
                }
                else
                {
                    StatusMessage = "取消导航";
                }
            });
        }

        #endregion

        #region Private Methods

        private async void LoadCategories()
        {
            try
            {
                var categories = await _productService.GetCategoriesAsync();
                Categories.Clear();
                foreach (var category in categories)
                {
                    Categories.Add(category);
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载分类失败: {ex.Message}";
            }
        }

        #endregion

        #region INavigationAware

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 检查是否是编辑模式
            if (navigationContext.Parameters.ContainsKey("ProductId"))
            {
                _isEditMode = true;
                _editingProductId = navigationContext.Parameters.GetValue<int>("ProductId");
                Title = "编辑产品";
                SaveButtonText = "更新";

                try
                {
                    var product = await _productService.GetProductByIdAsync(_editingProductId);
                    if (product != null)
                    {
                        // 创建产品的副本以避免直接修改原对象
                        Product = new Product
                        {
                            Id = product.Id,
                            Name = product.Name,
                            Description = product.Description,
                            Price = product.Price,
                            Stock = product.Stock,
                            Category = product.Category,
                            IsActive = product.IsActive,
                            CreateDate = product.CreateDate
                        };
                    }
                }
                catch (Exception ex)
                {
                    StatusMessage = $"加载产品数据失败: {ex.Message}";
                }
            }
            else
            {
                _isEditMode = false;
                _editingProductId = 0;
                Title = "添加产品";
                SaveButtonText = "保存";
                Product = new Product();
            }

            LoadCategories();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 清理工作
        }

        #endregion
    }
}